#include<iostream>
#include<string>
#include<unistd.h>
#include<fcntl.h>

void SetNonBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if(fl < 0)
    {
        perror("fcntl");
        return;
    }
    fcntl(fd, F_SETFL, fl|O_NONBLOCK);  //让该fd以非阻塞方式工作
}

int main()
{
    char buffer[1024];
    std::string tips = "Please Enter#";
    SetNonBlock(0);
    while(1)
    {
        write(1, tips.c_str(), tips.size());
        //非阻塞，如果不输入，数据不就绪，以出错形式返回
        int n = read(0, buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout<<"echo#"<< buffer <<std::endl;
        }
        else if(n==0){
            std::cout<<"read file end!"<<std::endl;
            break;
        }
        else{
            if(errno == EAGAIN || errno == EWOULDBLOCK){
                std::cout<<"底层数据没有就绪"<<std::endl;
                sleep(1);

                continue;
            }
            else if(errno == EINTR){
                std::cout<<"被中断，重新来"<<std::endl;
                sleep(1);

                continue;
            }
            else
                std::cout<<"read error"<<std::endl;
        }
    }
    return 0;
} 